/* 
 * Plugin jquery sur les widgets
 * 
 */

(function($) {
    var nb_widget;
    var adress = "https://localhost/GWIT_Plateform_Trading/web/app_dev.php/";
    
    var methods = {
        init: function(){
            
        },
        show : function (){
            $(this).each(function(){
                $(this).show();
            });
        },
        
        hide : function (){
            $(this).each(function(){
                $(this).hide();
            });
        }
    }
    
    $.fn.widget = function(method){
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
        }    
    };
    
    //Hide widget (select ur menu)
    $.fn.widget_show_by_monitor = function(id_monitor){
        var defaults = {};
                        
        var options = $.extend(defaults, options);
                        
        return this.each(function(){
            obj = $(this);
            //Ajout du nouveau  du widget moniteur dans le center
            if ($(this).attr('m-id') == id_monitor){
                $(this).show();
            }else{
                $(this).hide();
            }
        });
    };
    
    //Ajsuter les paramètres css
    $.fn.widget_setcss = function(widget){
        var defaults = {};
                        
        var options = $.extend(defaults, options);
                        
        return this.each(function(){
            
            });
    };
    
    
    //Ajout du widget dans le menu div
    $.fn.widget_add_menu = function(widget_name, monitor_id, widget_id){
        
        var defaults = {};
                        
        var options = $.extend(defaults, options);
                        
        return this.each(function(){
            obj = $(this);
            //Ajout du nouveau  du widget moniteur dans le center
            obj.append(
                '<li class="li_grey wiget_list" m-id='+monitor_id+' w-id='+widget_id+'>'+
                '<a  href="#'+widget_name+'" style="float:left;">'+
                '<div style="width:176px;position:relative;float:left">' +
                '<i class="icon-ok"></i>'+
                '<span style="width:500px;"> '+widget_name+'</span></div>'+
                '<div style="margin-top:-3px;float:right;position:relative">'+
                '<div class="btn" style="margin:3px 1px -1px 1px;padding:1px;"><i class="icon-pencil icon-black"></i></div>'+
                '<div class="btn" style="margin:3px 1px -1px 5px;padding:1px;"><i class="icon-trash icon-black"></i></div>'+
                '</div>'+
                '</a> '+
                '</li>'
                );
        });
    };
    
    //Ajout d'un nouveau moniteur dans le layout #monitor
    $.fn.widget_add_layout = function(widget_name, monitor_id, widget_id){
        
        var defaults = {};
                        
        var options = $.extend(defaults, options);
                        
        return this.each(function(){
            obj = $(this);
            
            //Ajout du nouveau  du widget moniteur dans le center
            obj.append(
                '<div id="'+widget_name+'" w-id='+widget_id+' class="widget modal box" style="position: absolute;  top:150px;left:1030px;z-index: 1; height:500px;width: 500px;margin:0;overflow:hidden">'+
                '<div class="widget-header modal-header box-header" style="border-bottom:1px solid #ddd;">'+
                '<h4 class="">'+
                '<span style="background:#fff">'+widget_name+'</span>'+
                '<i class="icon-signal" style="float:left;margin:1px 5px 0px 0px;"></i>'+
                '<a class="box-btn" title="close"><i class="icon-trash"></i></a>'+
                '<a class="box-btn" title="toggle"><i class="icon-minus"></i></a> '    +
                '<a class="box-btn" title="config" data-toggle="modal" href="#box-config-modal"><i class="icon-cog"></i></a>'+
                '<a class="box-btn" style="margin-right:10px;" title="config" data-toggle="modal" href="#box-config-modal"><i class="icon-move"></i></a>'+
                '</h4>'+
                '</div>'+
                '<div id="'+widget_name+'_body" class="modal-body">'+
                '<div id="'+widget_name+'_container" style="width: 400px; height: 400px; margin: 0 auto; overflow:auto"></div>'+
                '</div>'+
                '</div>'
                );
                
            /*********** Evenement lié aux widgets  ***********/
            
            $("#"+widget_name).draggable({
                cursor: "move",
                handle: ".widget-header" ,
                snap: ".widget", 
                snapMode: "outer", 
                snapTolerance: "10"
            });
            //$( ".title_to_drag" ).draggable({helper: "clone",cursor: "move"});
                
            $("#"+widget_name+" .widget-header i.icon-move" ).draggable({
                helper: function( event ) {
                    return $( "<div class='ui-widget-header widget-header' style='z-index:100'>I'm a custom helper</div>" );
                }
                ,
                cursor: "move"
            });
            
            //WIDGET: REZISABLE
            $("#"+widget_name).resizable({
                maxHeight: 700,
                maxWidth: 700,
                minHeight: 100,
                minWidth: 200
            });
                
            $("#"+widget_name).on("mousedown", function() {
                var nb_widget_total = $(".widget").size();
                //console.log("Nombre total de widget : "+nb_widget_total);
                //console.log($(this).parent().parent().parent().attr("m-id"));
                var what_zindex = parseInt($(this).css("z-index"));
                var widget_to_modify = $(this);
                $(".widget").each(function () {
                    if ( parseInt($(this).css("z-index")) > what_zindex) {
                        $(this).css("z-index","-=1");
                    }
                });
                widget_to_modify.css("z-index",nb_widget_total);
            /*alert(what_zindex);*/
            });
        });
    };
})(jQuery);

var adress = "https://localhost/GWIT_Plateform_Trading/web/app_dev.php/";

/********************************* Foncton Javascript  ********************************************/

/**
 * Fonction de creation d'un widget dans la page et d'enregistrement en base de donnée
 *
 * @param menu = Selector du menu
 * @param layout = selector du layout
 * @param widget_name = recuperation du nom du widget
 * @param monitor_id = id du moniteur dans lequel enregistrer le widget
 */
function widget_save(menu,layout,widget_name, monitor_id){
    /************** Enregistrement dans la base de donnée ***************/
    $.ajaxSetup({
        async:false
    });
            
    var json = '{"name": "'+widget_name+'","monitor": "'+monitor_id+'"}';
    $.ajax({
        url: adress+"widget/save",
        type:"POST",
        contentType: 'application/json',
        data: json,
        dataType: 'json',
        success:function (data) {
            //console.log(data["name"]);
            console.log("Send data!");
            $(menu).widget_add_menu($("#add-widget-name").val(), monitor_id, data["id"]);
            //Ajout du widget dans le monitor
            $(layout).widget_add_layout($("#add-widget-name").val(), monitor_id, data["id"]);
        },
        error:function (xhr, ajaxOptions, thrownError){
        //alert(xhr.status);
        //alert(thrownError);
        }
    });
            
    $.ajaxSetup({
        async:true
    });
}

/**
 * Mise à jour d'un widget
 * @param widget_id : id du widget
 * 
 */
function widget_update(widget_id){
    
    var lock = $(".widget_zone div[w-id="+widget_id+"]").position();
    // coordX = left, coordY = top
    var coord = '"coordX" :"'+ $(".widget_zone div[w-id="+widget_id+"]").css("left")+'", "coordY" :"'+$(".widget_zone div[w-id="+widget_id+"]").css("top")+'"';
    var size = '"width" : '+ $(".widget_zone div[w-id="+widget_id+"]").width() + ', "height" :'+$(".widget_zone div[w-id="+widget_id+"]").height();
    var position = '"position" :'+$(".widget_zone div[w-id="+widget_id+"]").css("z-index");
    //console.log(position);
    var json = '{"id" : '+ widget_id+','+coord+','+size+','+position+'}';
    
    //Ajax request async
    $.ajax({
        url: adress+"widget/update",
        type:"POST",
        contentType: 'application/json',
        data: json,
        success:function (data) {
        },
        error:function (xhr, ajaxOptions, thrownError){
        //alert(xhr.status);
        //alert(thrownError);
        }
    });
}

function widget_delete(widget_id){
    
}

/**
 * Ajuste le CSS enregistrer lors de la derniere session
 */
function setCss(id, coordX, coordY, width, height, position){
    coordX+= "";
    coordY+="";
    console.log((coordX).match(/\d+/));
    $(".widget_zone div[w-id='"+id+"']").css({
        "left" : coordX,
        "top" : coordY,
        "z-index" : position,
        "height" : height,
        "width" : width
    });
}